package middleware

import (
	"context"
	"gitee.com/Cauchy_AQ/vxopen/api/internal/common"
	"gitee.com/Cauchy_AQ/vxopen/api/internal/errors"
	"gitee.com/Cauchy_AQ/vxopen/pkg/jwt"
	"github.com/zeromicro/go-zero/rest/httpx"
	"net/http"
	"strings"
)

type AuthMiddleware struct {
}

func NewAuthMiddleware() *AuthMiddleware {
	return &AuthMiddleware{}
}

func (m *AuthMiddleware) Handle(next http.HandlerFunc) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		authHeader := r.Header.Get("Authorization")
		if authHeader == "" {
			httpx.OkJsonCtx(r.Context(), w,
				common.NewCodeError(http.StatusUnauthorized, errors.ErrorMissAuthorization.Error()).(*common.CodeError).Data())
			return
		}
		// 按空格分割 Bearer token
		parts := strings.SplitN(authHeader, " ", 2)
		if !(len(parts) == 2 && parts[0] == "Bearer") {
			httpx.OkJsonCtx(r.Context(), w,
				common.NewCodeError(http.StatusUnauthorized, errors.ErrorAuthorization.Error()).(*common.CodeError).Data())
			return
		}
		myClaims, err := jwt.ParseToken(parts[1])
		if err != nil {
			httpx.OkJsonCtx(r.Context(), w,
				common.NewCodeError(common.InvalidTokenCode, errors.ErrorInvalidToken.Error()).(*common.CodeError).Data())
			return
		}

		/* metadata 传输数据
		md := metadata.Pairs("name", "cauchy")
		ctx := metadata.NewOutgoingContext(r.Context(), md)
		newReq := r.WithContext(ctx)
		*/

		ctx := context.WithValue(r.Context(), "MyClaims", *myClaims)
		next(w, r.WithContext(ctx))
	}
}
